How to use typedef for a Struct in C?

您所在的位置:网站首页 typedef extern How to use typedef for a Struct in C?

How to use typedef for a Struct in C?

2024-06-22 19:46| 来源: 网络整理| 查看: 265

In C, we use typedef to create aliases for already existing types. For structure, we can define a new name that can be used in place of the original struct name. In this article, we will learn how to create a typedef for a structure in C++.

Use the typedef struct in C

To create an alias for a structure in C, we can use the typedef keyword typedef for a structure that provides the existing datatype with a new name.

Syntax

For defining the structure and creating a typedef simultaneously use:

typedef struct StructName { // Member definitions} TypedefName;

For defining the Structure first, then creating a typedef use:

struct StructName { // Member definitions};typedef struct StructName TypedefName; C Program to Create an Alias Using typedef for a struct

The below program demonstrates the use typedef keyword to create a typedef for a structure in C.

C

// C program to create a typedef for a structure #include    // Defining the structure struct Student {     char name[50];     int age;     float gpa; };    // Creating a typedef for the struct typedef struct Student St;    int main() {     // Declaring a variable using the typedef     St student1;        // Assigning values to the struct members     snprintf(student1.name, sizeof(student1.name), "Ram");     student1.age = 20;     student1.gpa = 9.5;        // Displaying the information of a student     printf("Student Information:\n");     printf("Name: %s\n", student1.name);     printf("Age: %d\n", student1.age);     printf("GPA: %.2f\n", student1.gpa);        return 0; } Output Student Information: Name: Ram Age: 20 GPA: 9.50

author 21211a4uyj Improve Next Article How to Use typedef for a Union in C? Please Login to comment...


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3